package com.easymin.weixin.exceptions;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class WxExceptionHandler implements HandlerExceptionResolver {

  private static final Logger logger = LoggerFactory.getLogger(WxExceptionHandler.class);

  private View defaultView;

  public void setDefaultView(View defaultView) {
    this.defaultView = defaultView;
  }

  @Override
  public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                       HttpServletResponse httpServletResponse, Object obj, Exception ex) {

    ModelAndView mv = new ModelAndView();

    Map<String, String[]> params = httpServletRequest.getParameterMap();
    if (null == params) {
      params = Maps.newHashMap();
    }
    ex.printStackTrace();
    logger.error("exception url: {},request params:{},ex: {}", httpServletRequest.getRequestURL(), JSON.toJSONString(params), ex);

    if (ex instanceof IllegalArgumentException) {

      String message = ex.getMessage();
      mv.getModel().put("code", 101);
      mv.getModel().put("message", message);
      mv.setView(this.defaultView);
      httpServletResponse.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());

      return mv;
    } else if (ex instanceof SignErrorException) {
      String message = ex.getMessage();
      mv.getModel().put("code", 401);
      mv.getModel().put("message", message);
      mv.setView(this.defaultView);
      httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());

      return mv;
    } else if (ex instanceof IpNotAllowedException) {

      String message = ex.getMessage();

      mv.getModel().put("code", 403);
      mv.getModel().put("message", message);
      mv.setView(this.defaultView);
      httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
      return mv;
    }
    return null;
  }
}
